﻿using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.IO.Ports;

namespace Sun.WebSocket.SerialPort.Center
{
  public class BoxAccessor
  {
    public BoxAccessor(IEventAggregator eventAggregator)
    {
      _EventAggregator = eventAggregator;
    }

    private readonly IEventAggregator _EventAggregator;

    /// <summary>
    /// 当前与主模块通讯通道
    /// </summary>
    private System.IO.Ports.SerialPort _MainSerialPort;

    private void MainSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
      try
      {
        System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;
        var buffer = new byte[sp.BytesToRead];
        sp.Read(buffer);
        _EventAggregator.MessageOnUiThread(new BoxDataMsg(buffer));
      }
      catch (Exception)
      {
        // 串口异常关闭，数据读取异常。
      }
    }

    public IList<string> GetPortNames()
    {
      return System.IO.Ports.SerialPort.GetPortNames();
    }

    public void Start(string portName, int rate)
    {
      _MainSerialPort = new System.IO.Ports.SerialPort(portName, rate);
      _MainSerialPort.DataReceived += MainSerialPort_DataReceived;
      _MainSerialPort.Open();
    }

    public void Stop()
    {
      _MainSerialPort?.Close();
    }

    internal void Send(byte[] rawData)
    {
      _MainSerialPort.Write(rawData);
    }

    internal void Send(string data)
    {
      _MainSerialPort.Write(data);
    }
  }
}